package com.viu.technology.controller;

import com.alibaba.fastjson.JSONObject;
import com.viu.technology.constant.OrderKey;
import com.viu.technology.dto.Result;
import com.viu.technology.dto.ResultCode;
import com.viu.technology.po.Order;
import com.viu.technology.service.order.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 秒杀api
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    /**
     * 使用MySQL锁方式
     * @param order
     * @param bindingResult
     * @return
     */
    @PostMapping("/generate/pessimism")
    public Result<Order> generate(@RequestBody @Validated Order order, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Result.fail(ResultCode.DATA_CHECK_FAILURE, bindingResult.getFieldError().getDefaultMessage());
        }

        Order order1 = orderService.pessimismGenerateOrder(order);

        if (order1 != null) {
            return Result.success(order1);
        }

        return Result.fail(ResultCode.SECKILL_END);

    }

    /**
     * 使用Redis方式
     * @param order
     * @param bindingResult
     * @return
     */
    @PostMapping("/generate/redis")
    public Result generateRedis(@RequestBody @Validated Order order, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(ResultCode.DATA_CHECK_FAILURE, bindingResult.getFieldError().getDefaultMessage());
        }

        //long startTime = System.currentTimeMillis();
        long getStock = redisTemplate.opsForValue().increment(OrderKey.SECKILL_STOCK.getKey() + order.getProductId(), -order.getProductCount());

        if (getStock < 0) {
            return Result.fail(ResultCode.SECKILL_END);
        }
        //log.info("耗时："+(System.currentTimeMillis()-startTime));

        Order order1 = orderService.redisGenerateOrder(order);

        if (null == order) {
            return Result.fail(ResultCode.DATA_INSERT_FAILURE);
        }


        return Result.success(order1);
    }

}
